using FrameWork;
using GameFrameWork;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

public class StorageConverter : JsonConverter
{
    private StorageModule _storageModule;

    public StorageConverter(StorageModule storageModule)
    {
        _storageModule = storageModule;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(StorageBase).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);

        string key = (string)jo[ProjectConfig.StroageKey];
        StorageBase storage = _storageModule.GetStorage(key);

        if (storage == null)
            throw new NullReferenceException("找不到对应的存档");

        serializer.Populate(jo.CreateReader(), storage);
        return storage;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
